<template>
	<view class="pb-150">
		<!-- 导航栏 -->
		<image src="/static/dingbu.png" class="mine-navbar-bg" :style="{ height: navbarHeight + 'rpx' }"
			mode="aspectFill">
		</image>
		<u-navbar title="品牌基地管理" :autoBack="true" leftIconColor="#fff" bgColor="transparent"
			:titleStyle="{ color: '#fff' }" safeAreaInsetTop placeholder></u-navbar>

		<!-- 搜索与筛选 -->
		<view class="filter-wrap bgff">
			<u-search v-model="query.keyword" placeholder="请输入基地名称" showAction actionText="搜索" @search="onSearch"
				:actionStyle="{ color: '#0A993B' }" :height="30" :inputStyle="{ fontSize: '28rpx' }" />

			<view class="row">
				<text class="label">行政区划</text>
				<view class="picker-input" @click="openRegionPicker">
					{{ query.region || '全部' }}
					<u-icon name="arrow-right" size="16" />
				</view>
			</view>

			<view class="row">
				<text class="label">树种</text>
				<u-picker :show="showSpecies" :columns="[species]" @confirm="onSpeciesConfirm"
					@cancel="showSpecies = false" />
				<view class="picker-input" @click="showSpecies = true">
					{{ query.tree || '全部' }}
					<u-icon name="arrow-right" size="16" />
				</view>
			</view>

			<!-- 导出数据按钮（移动到树种下面） -->
			<view class="export-row">
			<u-button class="btn-export" text="导出数据" @click="handleExportClick"
					:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }" />
			</view>
		</view>

		<!-- 列表 -->
		<view v-if="loading && pageNum === 1" class="loading-wrap">
			<u-loading-icon mode="spinner" size="28" />
			<text class="loading-text">加载中...</text>
		</view>

		<view v-else-if="!loading && filteredList.length === 0" class="empty-wrap">
			<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png" />
		</view>

		<view v-else>
		<view v-for="item in filteredList" :key="item.id" class="card">
			<view class="card-hd">
				<text class="title">{{ item.name }}</text>
				<view class="tag">{{ item.tag }}</view>
			</view>
			<view class="kv">行政区划：{{ item.region }}</view>
			<view class="kv">通讯地址：{{ item.address }}</view>
			<view class="kv">负责人：{{ item.leader }} 联系电话：{{ item.phone }}</view>
			<view class="kv">树种：{{ item.tree }}</view>
			<view class="kv">认证时间：{{ item.certStart }} 有效期：{{ item.certEnd }}</view>
			<view class="ops">
				<u-button size="small" text="编辑" @click="onEdit(item)"
						:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff' }" />
				<u-button size="small" text="删除" type="error" plain @click="onDelete(item)"
						:customStyle="{ border: '1px solid #0A993B', color: '#0A993B' }" />
				<u-button size="small" text="详情" plain @click="onView(item)" />
				</view>
			</view>

			<!-- 加载更多 -->
			<view v-if="loading && pageNum > 1" class="loading-more">
				<u-loading-icon mode="spinner" size="24" />
				<text class="loading-text">加载更多...</text>
			</view>

			<!-- 没有更多数据 -->
			<view v-if="!hasMore && filteredList.length > 0" class="no-more">
				<text class="no-more-text">没有更多数据了</text>
			</view>
		</view>
		<view @tap="submit()" class="w-690 h-88 br-16 fixed rowsc rowsm fs-36 colfff bg"
			style="bottom: 68rpx;left: 30rpx;">
			添加品牌基地
		</view>
		<!-- 详情弹窗 -->
		<u-popup :show="showDetail" mode="center" round="12" @close="showDetail = false" :customStyle="{ zIndex: 9997 }">
			<view class="detail-wrap">
				<view class="detail-title">{{ currentItem.name }}</view>
				<view class="detail-line">行政区划：{{ currentItem.region }}</view>
				<view class="detail-line">地址：{{ currentItem.address }}</view>
				<view class="detail-line">负责人：{{ currentItem.leader }}（{{ currentItem.phone }}）</view>
				<view class="detail-line">树种：{{ currentItem.tree }}</view>
				<view class="detail-line">认证：{{ currentItem.certStart }} - {{ currentItem.certEnd }}</view>
				<u-button text="关闭" @click="showDetail = false" />
			</view>
		</u-popup>



		<!-- 添加品牌基地弹窗 -->
		<u-popup :show="showAdd" mode="center" round="12" @close="showAdd = false" :closeable="true"
			:customStyle="{ zIndex: 10002 }">
			<view class="add-wrap">
				<view class="add-header">
					<text class="add-title">{{ isEditMode ? '编辑品牌基地' : '添加品牌基地' }}</text>
				</view>

				<scroll-view scroll-y class="add-form">
					<view class="form-row">
						<text class="form-label">类型</text>
						<u-picker :show="showType" :columns="[types]" @confirm="typeConfirm" @cancel="showType = false" />
						<view class="form-input" @click="showType = true">
							{{ addForm.type || '请选择类型' }}
							<u-icon name="arrow-down" size="16" />
						</view>
					</view>

					<view class="form-row">
						<text class="form-label">行政区划</text>
						<view class="form-input" @click="openAddRegionPicker">
							{{ addForm.region || '请选择行政区划' }}
							<u-icon name="arrow-down" size="16" />
						</view>
					</view>

					<view class="form-row">
						<text class="form-label">基地名称</text>
						<u--input v-model="addForm.name" placeholder="请输入" class="form-input" />
					</view>

					<view class="form-row">
						<text class="form-label">通讯地址</text>
						<u--input v-model="addForm.address" placeholder="请输入" class="form-input" />
					</view>

					<view class="form-row">
						<text class="form-label">负责人</text>
						<u--input v-model="addForm.leader" placeholder="请输入" class="form-input" />
					</view>

					<view class="form-row">
						<text class="form-label">联系电话</text>
						<u--input v-model="addForm.phone" placeholder="请输入" class="form-input" />
					</view>

					<view class="form-row">
						<text class="form-label">认证时间</text>
						<u-datetime-picker :show="showCertStart" mode="date" @confirm="certStartConfirm"
							@cancel="showCertStart = false" v-model="addForm.certStartTimestamp" />
						<view class="form-input" @click="showCertStart = true">
							{{ addForm.certStart || '请选择' }}
							<u-icon name="calendar" size="16" />
						</view>
					</view>

					<view class="form-row">
						<text class="form-label">有效期</text>
						<u-datetime-picker :show="showCertEnd" mode="date" @confirm="certEndConfirm"
							@cancel="showCertEnd = false" v-model="addForm.certEndTimestamp" />
						<view class="form-input" @click="showCertEnd = true">
							{{ addForm.certEnd || '请选择' }}
							<u-icon name="calendar" size="16" />
						</view>
					</view>

					<view class="form-row">
						<text class="form-label">树种</text>
						<u-picker :show="showAddSpecies" :columns="[species]" @confirm="addSpeciesConfirm"
							@cancel="showAddSpecies = false" />
						<view class="form-input" @click="showAddSpecies = true">
							{{ addForm.tree || '请选择树种' }}
							<u-icon name="arrow-down" size="16" />
						</view>
					</view>

					<view class="form-row">
						<text class="form-label">地图定位</text>
						<u--input v-model="addForm.location" placeholder="请选择位置" class="form-input" readonly
							@click.stop="openMapSelect" />
					</view>


					<!-- 内嵌地图选择器（放在弹窗内） -->
					<zhuo-tianditu-select ref="tMap" inline :icon="mapIcon" :searchType="0" :api-key="mapApiKey"
						@onLoad="onMapLoad" @onSelect="onMapSelect">
					</zhuo-tianditu-select>

					<!-- API Key配置提示 -->
					<!-- <view class="form-row" style="margin-top: 20rpx;">
											<text style="color: #FF6B6B; font-size: 24rpx;">
												⚠️ 请先配置有效的天地图API Key才能使用地图功能
											</text>
										</view> -->
					<view class="add-actions" style="position:relative;z-index:10003;">
						<u-button text="取消" @click="showAdd = false"
							:customStyle="{ background: '#fff', borderColor: '#ddd', color: '#333', flex: 1, marginRight: '16rpx' }" />
						<u-button :text="isEditMode ? '保存' : '确认'" @click="handleSubmit"
							:customStyle="{ background: '#0A993B', borderColor: '#0A993B', color: '#fff', flex: 1 }" />
					</view>
				</scroll-view>


			</view>
		</u-popup>
		<!-- 选择器 -->
		<u-picker :show="showSpecies" :columns="[species]" @confirm="onSpeciesConfirm" @cancel="showSpecies = false"
			:customStyle="{ zIndex: 9999 }" />
		<!-- 搜索用的行政区划三级选择器 -->
		<u-picker :show="regionPickerShow" :columns="regionColumns" @confirm="onRegionConfirm"
			@cancel="regionPickerShow = false" @change="onRegionPickerChange" @close="regionPickerShow = false"
			:customStyle="{ zIndex: 9999 }" />
		<!-- 添加表单用的行政区划三级选择器 -->
		<u-picker :show="addRegionPickerShow" :columns="addRegionColumns" @confirm="onAddRegionConfirm"
			@cancel="addRegionPickerShow = false" @change="onAddRegionPickerChange" @close="addRegionPickerShow = false"
			:customStyle="{ zIndex: 2 }" />

		<image src="" mode=""></image>
	</view>
</template>

<script>
import navbarMixin from '@/common/navbarMixin'
import {
	getBrandBaseList,
	getTreeSpeciesList,
	getDeptList,
	addBrandBase,
	updateBrandBase,
	delJjlBrandBase,
	editJjlBrandBase,
	exportJjlBrandBase
} from '@/api/economicforest'
// 预览用地图组件
import TiandituMap from '@/uni_modules/zhuo-tianditu-select/components/zhuo-tianditu-select/tianditu-map.vue'

export default {
	mixins: [navbarMixin],
	components: {
		'tianditu-map': TiandituMap
	},
	data() {
		return {
			// 地图预览相关
			mapApiKey: '80485f9d414a68e137dc073101f7900f',
			mapPreviewHeight: '220px',
			mapPreviewLonLat: {
				lon: null,
				lat: null
			},
			query: {
				keyword: '',
				region: '全部',
				tree: '全部'
			},
			regions: ['全部'],
			species: ['全部'],
			showRegion: false,
			showSpecies: false,
			list: [],
			loading: false,
			pageNum: 1,
			pageSize: 10,
			hasMore: true,
			showDetail: false,
			currentItem: {},
			showAdd: false,
			addForm: {
				type: '',
				region: '',
				name: '',
				address: '',
				leader: '',
				phone: '',
				certStart: '',
				certEnd: '',
				tree: '',
				location: '',
				certStartTimestamp: 0,
				certEndTimestamp: 0,
				deptId: '',
				treeSpeciesId: ''
			},
			showType: false,
			showAddRegion: false,
			showCertStart: false,
			showCertEnd: false,
			showAddSpecies: false,
			types: ['地理标志', '非地理标志'],
			isEditMode: false, // 新增：编辑模式标志
			editItemId: null, // 新增：编辑时需要记录的项ID

			// API参数
			apiParams: {
				pageNum: '1',
				pageSize: '10',
				deptId: '',
				treeSpeciesId: ''
			},
			// 行政区划树形数据
			regionData: [],
			// 搜索用的行政区划三级选择器状态
			regionPickerShow: false,
			regionColumns: [
				[],
				[],
				[]
			],
			pIndex: 0,
			cIndex: 0,
			userSelectedLevel: 1, // 记录用户实际选择的层级
			// 添加表单用的行政区划三级选择器状态
			addRegionPickerShow: false,
			addRegionColumns: [
				[],
				[],
				[]
			],
			addPIndex: 0,
			addCIndex: 0,
			addUserSelectedLevel: 1, // 记录添加表单中用户实际选择的层级
			// 映射表
			speciesIdMap: {},
			deptIdMap: {},


			// 地图图标
			mapIcon: null,

			// 导出相关数据
			exportProp: {
				exportData: [],
				exportName: '品牌基地数据',
				hideTimeName: false,
				sheetNameList: ['基地名称', '类型', '行政区划', '通讯地址', '负责人', '联系电话', '树种', '认证时间', '有效期']
			},

		}
	},
	computed: {
		filteredList() {
			const kw = this.query.keyword || ''
			return (this.list || []).filter(v => {
				const okKw = !kw || (v.name && v.name.includes(kw))
				const okRg = (this.query.region === '全部') || v.region === this.query.region
				const okSp = (this.query.tree === '全部') || v.tree === this.query.tree
				return okKw && okRg && okSp
			})
		}
	},
	onLoad() {
		console.log('=== 页面加载开始 ===')
		console.log('初始exportProp:', this.exportProp)
		
		// 检查当前运行环境
		const systemInfo = uni.getSystemInfoSync()
		console.log('当前运行环境:', systemInfo.platform)
		console.log('将使用CSV导出方案（兼容性更好）')
		
		this.getBrandBaseList()
		this.getTreeSpeciesList()
		this.getDeptList()
		this.initMapIcon()
		// 准备导出数据
		this.prepareExportData()
		
		console.log('页面加载完成，准备导出数据')
		
		// 尝试预加载天地图脚本（如果组件存在则初始化默认坐标）
		this.$nextTick(() => {
			const tryInit = () => {
				const tmap = this.$refs.tMap
				if (tmap && tmap.$refs && tmap.$refs.tiandituMapRefs && tmap.$refs.tiandituMapRefs.initCharts) {
					try {
						// 使用默认北京经纬度初始化，主要是为了预加载脚本
						tmap.$refs.tiandituMapRefs.initCharts(116.397128, 39.916527)
						console.log('已尝试预初始化天地图')
						return
					} catch (e) {
						console.warn('预初始化地图失败', e)
					}
				}
				// 若未准备好，最多重试两次
				if (!this._tmapInitRetry) this._tmapInitRetry = 0
				if (this._tmapInitRetry < 2) {
					this._tmapInitRetry++
					setTimeout(tryInit, 800)
				}
			}
			tryInit()
		})
	},
	methods: {
		// 初始化地图图标
		initMapIcon() {
			// 自定义图片 - 参考官方示例
			const that = this
			uni.getImageInfo({
				src: '/static/0c61bddbe22455f0f1532005e0507bd6.png', // 使用现有的图标
				success(res) {
					that.mapIcon = res.path
				},
				fail(err) {
					console.log('地图图标加载失败:', err)
					that.mapIcon = null
				}
			})
		},

		// 更新只读预览地图到指定经纬度
		updatePreviewMap(lon, lat) {
			this.mapPreviewLonLat.lon = lon
			this.mapPreviewLonLat.lat = lat
			const cmp = this.$refs.previewMap
			if (!cmp) return
			// 如果有坐标则初始化或更新地图显示
			if (lon != null && lat != null) {
				if (cmp.initCharts) {
					try {
						cmp.initCharts(parseFloat(lon), parseFloat(lat))
					} catch (e) {
						/* ignore */
}
				} else if (cmp.upDataCharts) {
					try {
						cmp.upDataCharts(parseFloat(lon), parseFloat(lat))
					} catch (e) {
						/* ignore */
}
				}
			}
		},

		// 地图加载完成
		onMapLoad() {
			console.log('天地图加载完成')
			// 检查API Key是否有效
			if (!this.$refs.tMap) {
				uni.showToast({
					title: '请先配置有效的天地图API Key',
					icon: 'none',
					duration: 3000
				})
			}
		},


		// 地图位置选择完成
		onMapSelect(value) {
			console.log('选择的位置:', value)
			if (value && value.address) {
				this.addForm.location = value.address
				if (value.location) {
					this.addForm.lon = value.location.lon
					this.addForm.lat = value.location.lat
					this.updatePreviewMap(this.addForm.lon, this.addForm.lat)
				}
			}
		},

		// 打开地图选择器
		openMapSelect() {
			console.log('打开地图选择器')
			// 检查 API Key
			if (!this.mapApiKey || String(this.mapApiKey).includes('填入')) {
				uni.showToast({
					title: '请先配置有效的天地图API Key',
					icon: 'none'
				})
				console.warn('未配置有效 mapApiKey')
				return
			}
			const tmap = this.$refs.tMap
			if (!tmap) {
				console.warn('未找到地图组件引用 $refs.tMap')
				uni.showToast({
					title: '地图组件未就绪，请稍后再试',
					icon: 'none'
				})
				return
			}
			
			// 如果表单中已有坐标，直接使用
			if (this.addForm.lon && this.addForm.lat) {
				try {
					if (typeof tmap.open === 'function') {
						console.log('使用现有坐标打开地图', this.addForm.lon, this.addForm.lat)
						return tmap.open(parseFloat(this.addForm.lon), parseFloat(this.addForm.lat))
					}
				} catch (e) {
					console.warn('调用 tMap.open 失败，尝试回退：', e)
				}
				// 回退：直接显示组件并初始化内部地图实例（如果可用）
				try {
					tmap.visible = true
					this.$nextTick(() => {
						const inner = tmap.$refs && tmap.$refs.tiandituMapRefs
						if (inner && inner.initCharts) {
							inner.initCharts(parseFloat(this.addForm.lon), parseFloat(this.addForm.lat))
						}
					})
				} catch (e) {
					console.error('回退显示地图失败', e)
					uni.showToast({
						title: '无法打开地图选择器',
						icon: 'none'
					})
				}
				return
			}
			
			// 获取当前位置
			this.getCurrentLocationForInlineMap(tmap)
		},
		
		// 获取当前位置用于内嵌地图显示
		getCurrentLocationForInlineMap(tmap) {
			uni.showLoading({
				title: '获取位置中...'
			})
			
			uni.getLocation({
				type: 'gcj02',
				altitude: false,
				success: (res) => {
					uni.hideLoading()
					console.log('获取到当前位置:', res)
					
					try {
						if (typeof tmap.open === 'function') {
							// 使用当前位置打开地图
							tmap.open(res.longitude, res.latitude)
						}
					} catch (e) {
						console.warn('调用 tMap.open 失败，尝试回退：', e)
						// 回退：直接显示组件并初始化内部地图实例
						try {
							tmap.visible = true
							this.$nextTick(() => {
								const inner = tmap.$refs && tmap.$refs.tiandituMapRefs
								if (inner && inner.initCharts) {
									inner.initCharts(res.longitude, res.latitude)
								}
							})
						} catch (e2) {
							console.error('回退显示地图失败', e2)
							uni.showToast({
								title: '无法打开地图选择器',
								icon: 'none'
							})
						}
					}
				},
				fail: (err) => {
					uni.hideLoading()
					console.error('获取位置失败:', err)
					
					// 获取位置失败，使用默认坐标（北京天安门）
					uni.showToast({
						title: '获取位置失败，使用默认位置',
						icon: 'none',
						duration: 2000
					})
					
					try {
						if (typeof tmap.open === 'function') {
							console.log('使用默认坐标打开地图')
							tmap.open(116.397128, 39.916527)
						}
					} catch (e) {
						console.warn('调用 tMap.open 失败，尝试回退：', e)
						// 回退：直接显示组件并初始化内部地图实例
						try {
							tmap.visible = true
							this.$nextTick(() => {
								const inner = tmap.$refs && tmap.$refs.tiandituMapRefs
								if (inner && inner.initCharts) {
									inner.initCharts(116.397128, 39.916527)
								}
							})
						} catch (e2) {
							console.error('回退显示地图失败', e2)
							uni.showToast({
								title: '无法打开地图选择器',
								icon: 'none'
							})
						}
					}
				}
			})
		},
		
		// 初始化地图使用当前位置
		initMapWithCurrentLocation() {
			try {
				const tmap = this.$refs.tMap
				if (tmap && typeof tmap.open === 'function') {
					// 获取当前位置
					uni.getLocation({
						type: 'gcj02',
						altitude: false,
						success: (res) => {
							console.log('初始化地图使用当前位置:', res)
							tmap.open(res.longitude, res.latitude)
						},
						fail: (err) => {
							console.error('获取位置失败，使用默认位置:', err)
							// 使用默认经纬度以触发地图加载
							tmap.open(116.397128, 39.916527)
						}
					})
				}
			} catch (e) {
				console.warn('尝试打开内嵌地图失败', e)
			}
		},


		// 获取品牌基地列表
		async getBrandBaseList() {
			if (this.loading || !this.hasMore) return

			this.loading = true

			try {
				const params = {
					pageNum: String(this.pageNum),
					pageSize: String(this.pageSize),
					name: this.query.keyword || undefined,
					treeSpeciesId: this.apiParams.treeSpeciesId || undefined,
					deptId: this.apiParams.deptId || undefined
				}

				// 移除 undefined 参数
				Object.keys(params).forEach(key => params[key] === undefined && delete params[key])

				console.log('获取品牌基地列表参数:', params)

				const response = await getBrandBaseList(params)

				if (response && response.code === 200) {
					const newList = response.rows || []

					// 映射 API 数据到本地结构
					const mappedList = newList.map(item => ({
						id: item.id,
						name: item.name,
						tag: item.typeId === 1 ? '地理标志' : '非地理标志',
						region: item.compartment || '',
						address: item.address1 || '',
						leader: item.linkman || '',
						phone: item.phone || '',
						tree: item.treeSpeciesName || '',
						certStart: item.authTime || '',
						certEnd: item.endTime || '',
						originalData: item // 保存原始数据
					}))

					if (this.pageNum === 1) {
						this.list = mappedList
					} else {
						this.list = [...this.list, ...mappedList]
					}

					this.hasMore = newList.length === this.pageSize
					if (this.hasMore) {
						this.pageNum++
					}
				} else {
					uni.showToast({
						title: response?.msg || '获取数据失败',
						icon: 'none'
					})
				}
			} catch (error) {
				console.error('获取品牌基地列表失败:', error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			} finally {
				this.loading = false
			}
		},

		// 获取树种列表
		async getTreeSpeciesList() {
			try {
				const response = await getTreeSpeciesList()
				if (response && response.length > 0) {
					// 使用label作为显示名称
					this.species = ['全部', ...response.map(item => item.label)]

					// 保存树种ID映射，用于API调用
					this.speciesIdMap = {}
					response.forEach(item => {
						this.speciesIdMap[item.label] = item.value
					})
				}
			} catch (error) {
				console.error('获取树种列表失败:', error)
			}
		},

		// 获取行政区划列表
		async getDeptList() {
			try {
				const response = await getDeptList()
				if (response && response.data && response.data.length > 0) {
					// 构建行政区划树形结构
					this.buildRegionTree(response.data)
				}
			} catch (error) {
				console.error('获取行政区划失败:', error)
			}
		},

		// 构建行政区划树形结构
		buildRegionTree(deptList) {
			// 找到顶级部门（parentId为0）
			const topLevel = deptList.filter(item => item.parentId === 0)

			// 递归构建树形结构
			const buildTree = (parentId) => {
				return deptList
					.filter(item => item.parentId === parentId)
					.map(item => ({
						label: item.deptName,
						value: item.deptId,
						children: buildTree(item.deptId)
					}))
			}

			// 构建完整的树形结构
			this.regionData = topLevel.map(item => ({
				label: item.deptName,
				value: item.deptId,
				children: buildTree(item.deptId)
			}))

			// 生成扁平化的选项列表（用于简单选择器）
			this.generateAreaOptions()
		},
		async ensureCitiesFor(pIdx) {
			const prov = this.regionData[pIdx]
			if (!prov) return
			if (prov.children && prov.children.length) {
				this.regionColumns.splice(1, 1, ['请选择', ...prov.children.map(c => c.label)])
				return
			}
			
			this.loadingCities = false
		},
		async ensureDistsFor(pIdx, cIdx) {
			const prov = this.regionData[pIdx]
			const city = prov?.children?.[cIdx]
			if (!city) {
				this.regionColumns.splice(2, 1, ['请选择'])
				return
			}
			if (city.children && city.children.length) {
				this.regionColumns.splice(2, 1, ['请选择', ...city.children.map(d => d.label)])
				return
			}
			this.loadingDists = true
			let dists = []
			try {
				await new Promise(resolve => {
					uni.request({
						url: '/dev-api/system/region/districts',
						method: 'GET',
						data: { city: city.value },
						success: (res) => {
							if (res && res.statusCode === 200 && Array.isArray(res.data)) {
								dists = (res.data || []).map(d => ({ label: d.name || d.label, value: d.code || d.value }))
							}
							resolve()
						},
						fail: () => resolve()
					})
				})
			} catch (_) { }
			this.loadingDists = false
		},
		// 添加表单的懒加载方法
		async ensureAddCitiesFor(pIdx) {
			const prov = this.regionData[pIdx]
			if (!prov) return
			if (prov.children && prov.children.length) {
				this.addRegionColumns.splice(1, 1, ['请选择', ...prov.children.map(c => c.label)])
				return
			}
			this.loadingAddCities = false
		},
		async ensureAddDistsFor(pIdx, cIdx) {
			const prov = this.regionData[pIdx]
			const city = prov?.children?.[cIdx]
			if (!city) {
				this.addRegionColumns.splice(2, 1, ['请选择'])
				return
			}
			if (city.children && city.children.length) {
				this.addRegionColumns.splice(2, 1, ['请选择', ...city.children.map(d => d.label)])
				return
			}
			this.loadingAddDists = false
		},

		// 生成扁平化的行政区划选项
		generateAreaOptions() {
			const options = ['全部']

			// 递归遍历树形结构，生成完整的路径
			const traverse = (nodes, path = '') => {
				nodes.forEach(node => {
					const currentPath = path ? `${path}/${node.label}` : node.label
					options.push(currentPath)

					// 保存路径到ID的映射
					if (!this.deptIdMap) this.deptIdMap = {}
					this.deptIdMap[currentPath] = node.value

					// 递归处理子节点
					if (node.children && node.children.length > 0) {
						traverse(node.children, currentPath)
					}
				})
			}

			traverse(this.regionData)
			this.regions = options
		},

		onSearch() {
			this.apiParams.pageNum = '1'
			this.pageNum = 1
			this.hasMore = true
			this.list = []
			this.getBrandBaseList()
			// 更新导出数据
			this.prepareExportData()
		},

		// 重置
		onReset() {
			this.query = {
				keyword: '',
				region: '全部',
				tree: '全部'
			}
			this.apiParams = {
				pageNum: '1',
				pageSize: '10',
				deptId: '',
				treeSpeciesId: ''
			}
			this.pageNum = 1
			this.hasMore = true
			this.list = []
			this.getBrandBaseList()
		},

		// —— 行政区划（三级） ——
		openRegionPicker() {
			// 重置用户选择层级
			this.userSelectedLevel = 1
			// 首次打开先加载省份
			if (!this.regionColumns[0].length) {
				this.initRegionColumns()
			}
			this.regionPickerShow = true
		},
		initRegionColumns() {
			const provs = this.regionData.map(p => p.label)
			// 初始状态所有列都加"请选择"，让用户可以滚动
			this.regionColumns = [
				['请选择', ...provs],
				['请选择'],
				['请选择']
			]
		},
		initAddRegionColumns() {
			const provs = this.regionData.map(p => p.label)
			// 初始状态所有列都加"请选择"，让用户可以滚动
			this.addRegionColumns = [
				['请选择', ...provs],
				['请选择'],
				['请选择']
			]
		},
		onRegionPickerChange(e) {
			const col = e?.columnIndex ?? e?.detail?.column
			const idx = e?.index ?? e?.detail?.value
			if (col === 0) {
				// 第一列有"请选择"，所以索引需要减1
				this.pIndex = Math.max(0, (idx || 1) - 1)
				this.cIndex = 0
				this.userSelectedLevel = 1 // 用户选择了第一列
				// 占位，随后刷新
				this.regionColumns.splice(1, 2, ['加载中...'], ['请选择'])
				this.ensureCitiesFor(this.pIndex).then(() => this.ensureDistsFor(this.pIndex, 0))
			} else if (col === 1) {
				// 第二列有"请选择"，所以索引需要减1
				this.cIndex = Math.max(0, (idx || 1) - 1)
				this.userSelectedLevel = 2 // 用户选择了第二列
				this.regionColumns.splice(2, 1, ['加载中...'])
				this.ensureDistsFor(this.pIndex, this.cIndex)
			} else if (col === 2) {
				this.userSelectedLevel = 3 // 用户选择了第三列
			}
		},
		onAddRegionPickerChange(e) {
			const col = e?.columnIndex ?? e?.detail?.column
			const idx = e?.index ?? e?.detail?.value
			if (col === 0) {
				// 第一列有"请选择"，所以索引需要减1
				this.addPIndex = Math.max(0, (idx || 1) - 1)
				this.addCIndex = 0
				this.addUserSelectedLevel = 1 // 用户选择了第一列
				// 占位，随后刷新
				this.addRegionColumns.splice(1, 2, ['加载中...'], ['请选择'])
				this.ensureAddCitiesFor(this.addPIndex).then(() => this.ensureAddDistsFor(this.addPIndex, 0))
			} else if (col === 1) {
				// 第二列有"请选择"，所以索引需要减1
				this.addCIndex = Math.max(0, (idx || 1) - 1)
				this.addUserSelectedLevel = 2 // 用户选择了第二列
				this.addRegionColumns.splice(2, 1, ['加载中...'])
				this.ensureAddDistsFor(this.addPIndex, this.addCIndex)
			} else if (col === 2) {
				this.addUserSelectedLevel = 3 // 用户选择了第三列
			}
		},
		onRegionConfirm(e) {
			// e.value 为选中标签数组，过滤占位项
			let vals = e?.value || []
			if (!Array.isArray(vals)) vals = [String(vals)]
			const clean = vals.filter(v => v && v !== '请选择' && v !== '加载中...')

			// 反查编码 - 根据用户实际选择的层级来确定
			const regionValue = []
			const regionText = []

			// 第一列：省份 - 只有当用户真正选择了省份时才添加
			if (this.userSelectedLevel >= 1 && clean[0]) {
				const prov = this.regionData.find(p => p.label === clean[0])
				if (prov) {
					regionValue.push(prov.value)
					regionText.push(prov.label)

					// 第二列：城市 - 只有当用户真正选择了第二列时才添加
					if (this.userSelectedLevel >= 2 && clean[1] && prov.children) {
						const city = prov.children.find(c => c.label === clean[1])
						if (city) {
							regionValue.push(city.value)
							regionText.push(city.label)

							// 第三列：区县 - 只有当用户真正选择了第三列时才添加
							if (this.userSelectedLevel >= 3 && clean[2] && city.children) {
								const dist = city.children.find(d => d.label === clean[2])
								if (dist) {
									regionValue.push(dist.value)
									regionText.push(dist.label)
								}
							}
						}
					}
				}
			}
			this.query.region = regionText.join('/') || '全部'
			
			// 使用最后一级的deptId
			if (regionValue.length > 0) {
				this.apiParams.deptId = regionValue[regionValue.length - 1]
			} else {
				this.apiParams.deptId = ''
			}
			
			this.regionPickerShow = false
			// 更新导出数据
			this.prepareExportData()
		},
		onAddRegionConfirm(e) {
			// e.value 为选中标签数组，过滤占位项
			let vals = e?.value || []
			if (!Array.isArray(vals)) vals = [String(vals)]
			const clean = vals.filter(v => v && v !== '请选择' && v !== '加载中...')

			// 反查编码 - 根据用户实际选择的层级来确定
			const regionValue = []
			const regionText = []

			// 第一列：省份 - 只有当用户真正选择了省份时才添加
			if (this.addUserSelectedLevel >= 1 && clean[0]) {
				const prov = this.regionData.find(p => p.label === clean[0])
				if (prov) {
					regionValue.push(prov.value)
					regionText.push(prov.label)

					// 第二列：城市 - 只有当用户真正选择了第二列时才添加
					if (this.addUserSelectedLevel >= 2 && clean[1] && prov.children) {
						const city = prov.children.find(c => c.label === clean[1])
						if (city) {
							regionValue.push(city.value)
							regionText.push(city.label)

							// 第三列：区县 - 只有当用户真正选择了第三列时才添加
							if (this.addUserSelectedLevel >= 3 && clean[2] && city.children) {
								const dist = city.children.find(d => d.label === clean[2])
								if (dist) {
									regionValue.push(dist.value)
									regionText.push(dist.label)
								}
							}
						}
					}
				}
			}
			this.addForm.region = regionText.join('/') || ''
			
			// 使用最后一级的deptId
			if (regionValue.length > 0) {
				this.addForm.deptId = regionValue[regionValue.length - 1]
			} else {
				this.addForm.deptId = ''
			}
			
			this.addRegionPickerShow = false
		},
		// 地区选择器确认
		onAreaConfirm(e) {
			const selectedArea = e.value[0]
			this.query.region = selectedArea

			// 设置对应的部门ID
			if (selectedArea !== '全部' && this.deptIdMap && this.deptIdMap[selectedArea]) {
				this.apiParams.deptId = this.deptIdMap[selectedArea]
			} else {
				this.apiParams.deptId = ''
			}

			this.showRegion = false
		},

		// 树种选择器确认
		onSpeciesConfirm(e) {
			const selectedSpecies = e.value[0]
			this.query.tree = selectedSpecies

			// 设置对应的树种ID
			if (selectedSpecies !== '全部' && this.speciesIdMap && this.speciesIdMap[selectedSpecies]) {
				this.apiParams.treeSpeciesId = this.speciesIdMap[selectedSpecies]
			} else {
				this.apiParams.treeSpeciesId = ''
			}

			this.showSpecies = false
			// 更新导出数据
			this.prepareExportData()
		},
		// 导出
		async exportData() {
			try {
				uni.showLoading({
					title: '准备导出数据...'
				})

				// 获取所有数据（不分页）
				const params = {
					pageNum: '1',
					pageSize: '10000', // 设置一个很大的值来获取所有数据
					name: this.query.keyword || undefined,
					treeSpeciesId: this.apiParams.treeSpeciesId || undefined,
					deptId: this.apiParams.deptId || undefined
				}

				// 移除 undefined 参数
				Object.keys(params).forEach(key => params[key] === undefined && delete params[key])

				const response = await getBrandBaseList(params)

				if (response && response.code === 200) {
					const dataList = response.rows || []
					
					if (dataList.length === 0) {
						uni.hideLoading()
						uni.showToast({
							title: '没有数据可导出',
							icon: 'none'
						})
						return
					}

					// 转换为导出格式
					const exportData = dataList.map(item => ({
						'基地名称': item.name || '',
						'类型': item.typeId === 1 ? '地理标志' : '非地理标志',
						'行政区划': item.compartment || '',
						'通讯地址': item.address1 || '',
						'负责人': item.linkman || '',
						'联系电话': item.phone || '',
						'树种': item.treeSpeciesName || '',
						'认证时间': item.authTime || '',
						'有效期': item.endTime || ''
					}))

					// 更新导出数据
					this.exportProp.exportData = exportData
					this.exportProp.exportName = `品牌基地数据_${this.query.keyword || '全部'}_${this.query.region || '全部'}_${this.query.tree || '全部'}`

					uni.hideLoading()
					uni.showToast({
						title: '数据准备完成，开始导出',
						icon: 'success',
						duration: 1500
					})
				} else {
					uni.hideLoading()
					uni.showToast({
						title: response?.msg || '获取数据失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('导出数据失败:', error)
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				})
			}
		},

		// 导出完成回调
		exportOver(filePath) {
			console.log('=== 导出完成回调 ===')
			console.log('导出完成，文件路径:', filePath)
			uni.showModal({
				title: '导出成功',
				content: `文件已保存到：${filePath}`,
				showCancel: false,
				confirmText: '确定'
			})
		},

		// 尝试手动加载插件
		tryManualLoadPlugin() {
			console.log('=== 尝试手动加载插件 ===')
			
			// 检查当前环境
			const systemInfo = uni.getSystemInfoSync()
			console.log('系统信息:', systemInfo)
			
			// 检查是否在App环境
			// #ifdef APP-PLUS
			console.log('当前在App环境，renderjs应该可用')
			// #endif
			
			// #ifdef H5
			console.log('当前在H5环境，renderjs不可用')
			// #endif
			
			// #ifdef MP-WEIXIN
			console.log('当前在微信小程序环境，renderjs不可用')
			// #endif
			
			// 尝试不同的路径
			const possiblePaths = [
				'@/uni_modules/k-xlsx-export/index.js',
				'../../uni_modules/k-xlsx-export/index.js',
				'/uni_modules/k-xlsx-export/index.js',
				'../../../uni_modules/k-xlsx-export/index.js'
			]
			
			console.log('可能的插件路径:', possiblePaths)
			
			// 由于renderjs加载失败，直接使用备用方案
			console.log('renderjs加载失败，将使用备用导出方案')
			uni.showToast({
				title: '将使用备用导出方案',
				icon: 'none',
				duration: 2000
			})
		},

		// 处理导出点击
		handleExportClick() {
			console.log('=== 导出按钮被点击 ===')
			console.log('当前exportProp:', this.exportProp)
			console.log('exportProp.exportData长度:', this.exportProp.exportData.length)
			
			// 直接使用备用导出方案
			console.log('使用备用导出方案（CSV格式）')
			this.fallbackExport()
		},

		// 备用导出方案
		async fallbackExport() {
			console.log('=== 使用备用导出方案 ===')
			try {
				uni.showLoading({
					title: '准备导出数据...'
				})

				// 获取所有数据（不分页）
				const params = {
					pageNum: '1',
					pageSize: '10000',
					name: this.query.keyword || undefined,
					treeSpeciesId: this.apiParams.treeSpeciesId || undefined,
					deptId: this.apiParams.deptId || undefined
				}

				Object.keys(params).forEach(key => params[key] === undefined && delete params[key])

				const response = await getBrandBaseList(params)

				if (response && response.code === 200) {
					const dataList = response.rows || []
					
					if (dataList.length === 0) {
						uni.hideLoading()
						uni.showToast({
							title: '没有数据可导出',
							icon: 'none'
						})
						return
					}

					// 转换为CSV格式
					const csvContent = this.convertToCSV(dataList)
					
					// 生成文件名
					const fileName = `品牌基地数据_${this.query.keyword || '全部'}_${this.query.region || '全部'}_${this.query.tree || '全部'}_${this.formatDate(new Date())}.csv`

					uni.hideLoading()
					
					// 调用后端导出接口
					this.downloadFile(csvContent, fileName)
					
				} else {
					uni.hideLoading()
					uni.showToast({
						title: response?.msg || '获取数据失败',
						icon: 'none'
					})
				}
			} catch (error) {
				uni.hideLoading()
				console.error('备用导出失败:', error)
				uni.showToast({
					title: '导出失败，请重试',
					icon: 'none'
				})
			}
		},

		// 转换为CSV格式
		convertToCSV(dataList) {
			const headers = ['基地名称', '类型', '行政区划', '通讯地址', '负责人', '联系电话', '树种', '认证时间', '有效期']
			const csvRows = [headers.join(',')]

			dataList.forEach(item => {
				const row = [
					`"${item.name || ''}"`,
					`"${item.typeId === 1 ? '地理标志' : '非地理标志'}"`,
					`"${item.compartment || ''}"`,
					`"${item.address1 || ''}"`,
					`"${item.linkman || ''}"`,
					`"${item.phone || ''}"`,
					`"${item.treeSpeciesName || ''}"`,
					`"${item.authTime || ''}"`,
					`"${item.endTime || ''}"`
				]
				csvRows.push(row.join(','))
			})

			return csvRows.join('\n')
		},

		// 下载文件
		downloadFile(content, fileName) {
			console.log('=== 开始下载文件 ===')
			console.log('文件名:', fileName)
			console.log('内容长度:', content.length)
			
			// #ifdef APP-PLUS
			console.log('App端下载文件')
			try {
				// 尝试多种方式转换字符串为ArrayBuffer
				let arrayBuffer
				let base64
				
				try {
					// 方式1：使用TextEncoder（现代浏览器）
					const encoder = new TextEncoder()
					arrayBuffer = encoder.encode(content)
					console.log('使用TextEncoder转换成功')
				} catch (e1) {
					console.log('TextEncoder不可用，尝试其他方式')
					try {
						// 方式2：手动转换
						const bytes = []
						for (let i = 0; i < content.length; i++) {
							const charCode = content.charCodeAt(i)
							if (charCode < 0x80) {
								bytes.push(charCode)
							} else if (charCode < 0x800) {
								bytes.push(0xc0 | (charCode >> 6))
								bytes.push(0x80 | (charCode & 0x3f))
							} else {
								bytes.push(0xe0 | (charCode >> 12))
								bytes.push(0x80 | ((charCode >> 6) & 0x3f))
								bytes.push(0x80 | (charCode & 0x3f))
							}
						}
						arrayBuffer = new Uint8Array(bytes)
						console.log('手动转换成功')
					} catch (e2) {
						console.error('所有转换方式都失败:', e1, e2)
						throw new Error('无法转换字符串为ArrayBuffer')
					}
				}
				
				// 转换为base64
				try {
					base64 = uni.arrayBufferToBase64(arrayBuffer)
					console.log('转换为base64成功')
				} catch (e3) {
					console.error('转换为base64失败:', e3)
					// 使用简单的base64编码
					base64 = btoa(unescape(encodeURIComponent(content)))
					console.log('使用简单base64编码成功')
				}
				
				console.log('开始保存到设备...')
				plus.io.requestFileSystem(plus.io.PUBLIC_DOWNLOADS, function(fs) {
					fs.root.getFile(fileName, { create: true }, function(fileEntry) {
						fileEntry.createWriter(function(writer) {
							writer.onwrite = function(e) {
								console.log('文件保存成功:', e.target.fileName)
								uni.showModal({
									title: '导出成功',
									content: `文件已保存到下载目录：${fileName}`,
									showCancel: false,
									confirmText: '确定'
								})
							}
							writer.writeAsBinary(base64)
						}, function(err) {
							console.error('创建文件写入器失败:', err)
							uni.showToast({
								title: '文件保存失败',
								icon: 'none'
							})
						})
					}, function(err) {
						console.error('创建文件失败:', err)
						uni.showToast({
							title: '创建文件失败',
							icon: 'none'
						})
					})
				}, function(err) {
					console.error('请求文件系统失败:', err)
					uni.showToast({
						title: '文件系统访问失败',
						icon: 'none'
					})
				})
			} catch (error) {
				console.error('App端下载失败:', error)
				uni.showToast({
					title: '下载失败: ' + error.message,
					icon: 'none'
				})
			}
			// #endif

			// #ifdef H5
			console.log('H5端下载文件')
			try {
				// H5端使用Blob下载
				const blob = new Blob([content], { type: 'text/csv;charset=utf-8;' })
				const link = document.createElement('a')
				const url = URL.createObjectURL(blob)
				link.setAttribute('href', url)
				link.setAttribute('download', fileName)
				link.style.visibility = 'hidden'
				document.body.appendChild(link)
				link.click()
				document.body.removeChild(link)
				URL.revokeObjectURL(url)
				
				uni.showToast({
					title: '文件已下载',
					icon: 'success'
				})
			} catch (error) {
				console.error('H5端下载失败:', error)
				uni.showToast({
					title: '下载失败: ' + error.message,
					icon: 'none'
				})
			}
			// #endif

			// #ifdef MP-WEIXIN
			console.log('微信小程序端')
			// 微信小程序端提示用户
			uni.showModal({
				title: '导出提示',
				content: '小程序暂不支持直接导出文件，请使用App版本',
				showCancel: false,
				confirmText: '确定'
			})
			// #endif
			
			// 通用方案：如果以上都不可用，尝试使用uni.downloadFile
			// #ifndef APP-PLUS
			// #ifndef H5
			// #ifndef MP-WEIXIN
			console.log('使用通用下载方案')
			try {
				// 将内容转换为base64
				const base64Content = btoa(unescape(encodeURIComponent(content)))
				const dataUrl = `data:text/csv;base64,${base64Content}`
				
				uni.downloadFile({
					url: dataUrl,
					success: function(res) {
						if (res.statusCode === 200) {
							uni.showToast({
								title: '文件已保存',
								icon: 'success'
							})
						}
					},
					fail: function(err) {
						console.error('通用下载失败:', err)
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						})
					}
				})
			} catch (error) {
				console.error('通用下载方案失败:', error)
				uni.showToast({
					title: '当前环境不支持文件下载',
					icon: 'none'
				})
			}
			// #endif
			// #endif
			// #endif
		},

		// 准备导出数据
		async prepareExportData() {
			console.log('=== 开始准备导出数据 ===')
			try {
				// 获取所有数据（不分页）
				const params = {
					pageNum: '1',
					pageSize: '10000', // 设置一个很大的值来获取所有数据
					name: this.query.keyword || undefined,
					treeSpeciesId: this.apiParams.treeSpeciesId || undefined,
					deptId: this.apiParams.deptId || undefined
				}

				// 移除 undefined 参数
				Object.keys(params).forEach(key => params[key] === undefined && delete params[key])

				console.log('导出请求参数:', params)
				console.log('当前查询条件:', this.query)
				console.log('当前API参数:', this.apiParams)

				const response = await getBrandBaseList(params)
				console.log('API响应:', response)

				if (response && response.code === 200) {
					const dataList = response.rows || []
					console.log('获取到的数据条数:', dataList.length)
					console.log('原始数据示例:', dataList[0])
					
					// 转换为导出格式
					const exportData = dataList.map(item => ({
						'基地名称': item.name || '',
						'类型': item.typeId === 1 ? '地理标志' : '非地理标志',
						'行政区划': item.compartment || '',
						'通讯地址': item.address1 || '',
						'负责人': item.linkman || '',
						'联系电话': item.phone || '',
						'树种': item.treeSpeciesName || '',
						'认证时间': item.authTime || '',
						'有效期': item.endTime || ''
					}))

					console.log('转换后的导出数据示例:', exportData[0])
					console.log('导出数据总条数:', exportData.length)

					// 更新导出数据
					this.exportProp.exportData = exportData
					this.exportProp.exportName = `品牌基地数据_${this.query.keyword || '全部'}_${this.query.region || '全部'}_${this.query.tree || '全部'}`
					
					console.log('更新后的exportProp:', this.exportProp)
					console.log('=== 导出数据准备完成 ===')
				} else {
					console.error('API响应错误:', response)
				}
			} catch (error) {
				console.error('准备导出数据失败:', error)
			}
		},
		onEdit(item) {
			this.isEditMode = true;
			this.editItemId = item.id;
			this.addForm = {
				...item
			}; // 复制现有数据到表单
			this.addForm.certStartTimestamp = new Date(this.addForm.certStart).getTime();
			this.addForm.certEndTimestamp = new Date(this.addForm.certEnd).getTime();

			// 从 originalData 中获取 deptId、treeSpeciesId、地址与坐标，优先使用 originalData 的字段
			if (item.originalData) {
				const od = item.originalData
				this.addForm.deptId = od.deptId || ''
				this.addForm.treeSpeciesId = od.treeSpeciesId || ''
				// 后端可能把回显地址放在 address2 字段
				this.addForm.location = od.address2 || item.address2 || this.addForm.location || ''
				this.addForm.lon = od.lon || item.lon || this.addForm.lon || ''
				this.addForm.lat = od.lat || item.lat || this.addForm.lat || ''
			} else {
				// 如果没有 originalData，尝试从 item 本身读取（如果有）
				this.addForm.location = item.address2 || item.location || this.addForm.location || ''
				this.addForm.lon = item.lon || this.addForm.lon || ''
				this.addForm.lat = item.lat || this.addForm.lat || ''
			}

			// 更新预览地图坐标（若有经纬度则显示，否则清空）
			if (this.addForm.lon && this.addForm.lat) {
				this.updatePreviewMap(parseFloat(this.addForm.lon), parseFloat(this.addForm.lat))
			} else {
				this.updatePreviewMap(null, null)
			}

			this.showAdd = true;
			// 确保内嵌地图在弹窗打开后初始化：尝试立即调用 open，如果失败则延迟重试一次
			this.$nextTick(() => {
				try {
					const tmap = this.$refs.tMap
					if (tmap && typeof tmap.open === 'function') {
						const lon = this.addForm.lon ? parseFloat(this.addForm.lon) : 116.397128
						const lat = this.addForm.lat ? parseFloat(this.addForm.lat) : 39.916527
						return tmap.open(lon, lat)
					}
				} catch (e) {
					console.warn('onEdit 尝试打开内嵌地图失败，准备延迟重试', e)
				}
				// 延迟重试，等待弹窗动画/布局完成
				setTimeout(() => {
					try {
						const tmap2 = this.$refs.tMap
						if (tmap2 && typeof tmap2.open === 'function') {
							const lon = this.addForm.lon ? parseFloat(this.addForm.lon) : 116.397128
							const lat = this.addForm.lat ? parseFloat(this.addForm.lat) : 39.916527
							tmap2.open(lon, lat)
						}
					} catch (e) {
						console.error('onEdit 延迟重试打开地图失败', e)
					}
				}, 500)
			})
		},
		async onDelete(item) {
			uni.showModal({
				title: '提示',
				content: `确定删除"${item.name}"吗？`,
				success: async ({
					confirm
				}) => {
					if (confirm) {
						try {
							const response = await delJjlBrandBase(item.id)
							console.log('删除品牌基地响应:', response);

							if (response && response.code === 200) {
								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
								// 重新加载列表
								this.pageNum = 1;
								this.hasMore = true;
								this.list = [];
								this.getBrandBaseList();
							} else {
								uni.showToast({
									title: response?.msg || '删除失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('删除品牌基地失败:', error);
							uni.showToast({
								title: '网络错误，请重试',
								icon: 'none'
							});
						}
					}
				}
			})
		},
		onView(item) {
			this.currentItem = item;
			this.showDetail = true
		},
		submit() {
			// 完全重置表单数据
			this.addForm = {
				type: '',
				region: '',
				name: '',
				address: '',
				leader: '',
				phone: '',
				certStart: this.formatDate(new Date()),
				certEnd: this.formatDate(new Date()),
				tree: '',
				location: '',
				certStartTimestamp: Date.now(),
				certEndTimestamp: Date.now(),
				deptId: '',
				treeSpeciesId: '',
				lon: '',
				lat: ''
			};
			this.isEditMode = false; // 确保是添加模式
			this.editItemId = null; // 清除编辑项ID
			this.showAdd = true; 
			// 打开弹窗后立即初始化内嵌地图选择器，确保弹窗中显示地图（只保留选择器一个地图）
			this.$nextTick(() => {
				this.initMapWithCurrentLocation()
			})
		},
		typeConfirm(e) {
			this.addForm.type = e.value[0];
			this.showType = false;
		},
		// 添加弹框中的行政区划选择器
		openAddRegionPicker() {
			// 重置用户选择层级
			this.addUserSelectedLevel = 1
			// 首次打开先加载省份
			if (!this.addRegionColumns[0].length) {
				this.initAddRegionColumns()
			}
			this.addRegionPickerShow = true
		},


		certStartConfirm(e) {
			// 将时间戳转换为 YYYY-MM-DD 格式
			const date = new Date(e.value);
			this.addForm.certStart = this.formatDate(date);
			this.showCertStart = false; 
		},
		certEndConfirm(e) {
			// 将时间戳转换为 YYYY-MM-DD 格式
			const date = new Date(e.value);
			this.addForm.certEnd = this.formatDate(date);
			this.showCertEnd = false; 
		},
		addSpeciesConfirm(e) {
			const selectedSpecies = e.value[0]
			this.addForm.tree = selectedSpecies

			// 设置对应的树种ID
			if (selectedSpecies !== '请选择树种' && this.speciesIdMap && this.speciesIdMap[selectedSpecies]) {
				this.addForm.treeSpeciesId = this.speciesIdMap[selectedSpecies]
			} else {
				this.addForm.treeSpeciesId = ''
			}

			this.showAddSpecies = false
		},

		handleSubmit() {
			if (this.isEditMode) {
				this.confirmEdit();
			} else {
				this.confirmAdd();
			}
		},
		async confirmAdd() {
			// 验证必填字段
			if (!this.addForm.name || !this.addForm.region || !this.addForm.tree) {
				uni.showToast({
					title: '请填写必填字段',
					icon: 'none'
				});
				return;
			}
			
			try {
				// 构造API请求数据
				const apiData = {
					typeId: this.addForm.type === '地理标志' ? 1 : 2, // 根据类型设置ID
					compartment: this.addForm.region,
				name: this.addForm.name,
					address1: this.addForm.address,
					linkman: this.addForm.leader,
				phone: this.addForm.phone,
					authTime: this.addForm.certStart,
					endTime: this.addForm.certEnd,
					treeSpeciesId: this.addForm.treeSpeciesId,
					lon: this.addForm.lon || '',
					lat: this.addForm.lat || '',
					address2: this.addForm.location || ''
				};

				console.log('添加品牌基地数据:', apiData);

				const response = await addBrandBase(apiData);
				console.log('添加品牌基地响应:', response);

				if (response && response.code === 200) {
					uni.showToast({
						title: '添加成功',
						icon: 'success'
					});
			this.showAdd = false;

					// 重新加载列表
					this.pageNum = 1;
					this.hasMore = true;
					this.list = [];
					this.getBrandBaseList();
			
			// 重置表单
			this.addForm = {
				type: '',
				region: '',
				name: '',
				address: '',
				leader: '',
				phone: '',
				certStart: '',
				certEnd: '',
				tree: '',
				location: '',
				certStartTimestamp: Date.now(),
						certEndTimestamp: Date.now(),
						deptId: '',
						treeSpeciesId: '',
						lon: '',
						lat: ''
					};


			
			// 重置编辑模式
			this.isEditMode = false;
			this.editItemId = null;
				} else {
					uni.showToast({
						title: response?.msg || '添加失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('添加品牌基地失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		},
		async confirmEdit() {
			// 验证必填字段
			if (!this.addForm.name || !this.addForm.region || !this.addForm.tree) {
				uni.showToast({
					title: '请填写必填字段',
					icon: 'none'
				});
				return;
			}
			
			try {
				// 构造API请求数据
				const apiData = {
					id: this.editItemId, // 编辑时需要传递ID
					typeId: this.addForm.type === '地理标志' ? 1 : 2, // 根据类型设置ID
					compartment: this.addForm.region,
					name: this.addForm.name,
					address1: this.addForm.address,
					linkman: this.addForm.leader,
					phone: this.addForm.phone,
					authTime: this.addForm.certStart,
					endTime: this.addForm.certEnd,
					treeSpeciesId: this.addForm.treeSpeciesId,
					lon: this.addForm.lon || '',
					lat: this.addForm.lat || '',
					address2: this.addForm.location || ''
				};

				console.log('修改品牌基地数据:', apiData);

				const response = await editJjlBrandBase(apiData);
				console.log('修改品牌基地响应:', response);

				if (response && response.code === 200) {
					uni.showToast({
						title: '修改成功',
						icon: 'success'
					});
				this.showAdd = false;

					// 重新加载列表
					this.pageNum = 1;
					this.hasMore = true;
					this.list = [];
					this.getBrandBaseList();
				
				// 重置表单和编辑状态
				this.addForm = {
					type: '',
					region: '',
					name: '',
					address: '',
					leader: '',
					phone: '',
					certStart: '',
					certEnd: '',
					tree: '',
					location: '',
					certStartTimestamp: Date.now(),
						certEndTimestamp: Date.now(),
						deptId: '',
						treeSpeciesId: '',
						lon: '',
						lat: ''
					};



				this.isEditMode = false;
				this.editItemId = null;
				} else {
					uni.showToast({
						title: response?.msg || '修改失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('修改品牌基地失败:', error);
				uni.showToast({
					title: '网络错误，请重试',
					icon: 'none'
				});
			}
		},
		// 格式化日期为 YYYY-MM-DD
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},

		// 下拉刷新
		onPullDownRefresh() {
			this.pageNum = 1
			this.hasMore = true
			this.getBrandBaseList().finally(() => {
				uni.stopPullDownRefresh()
			})
		},

		// 上拉加载更多
		onReachBottom() {
			if (this.hasMore && !this.loading) {
				this.getBrandBaseList()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.mine-navbar-bg {
	position: fixed;
	top: 0;
	left: 0;
	width: 750rpx;
	
	z-index: 1;
}

.filter-wrap {
	padding: 20rpx;
}

.row {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin-top: 16rpx;
}

.label {
	color: #333;
	width: 150rpx;
}

.picker-input {
	flex: 1;
	height: 72rpx;
	padding: 0 20rpx;
	background: #fff;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: flex-end;
	color: #666;
}

.btn-export {
	margin-left: auto;
}

.export-row {
	display: flex;
	justify-content: flex-end;
	margin-top: 16rpx;
}

.card {
	margin: 16rpx 20rpx;
	padding: 20rpx;
	background: #fff;
	border-radius: 16rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
}

.card-hd {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 8rpx;
}

.title {
	font-size: 30rpx;
	font-weight: 600;
	color: #333;
}

.tag {
	background: #e8f6ee;
	color: #0A993B;
	padding: 6rpx 14rpx;
	border-radius: 20rpx;
	font-size: 22rpx;
}

.kv {
	margin-top: 8rpx;
	color: #333;
}

.ops {
	margin-top: 14rpx;
	display: flex;
	gap: 12rpx;
}

.detail-wrap {
	width: 640rpx;
	padding: 24rpx;
}

.detail-title {
	text-align: center;
	font-size: 30rpx;
	font-weight: 600;
	margin-bottom: 12rpx;
}

.detail-line {
	margin: 10rpx 0;
	color: #333;
}

.add-wrap {
	width: 700rpx;
	padding: 20rpx;
}

.add-header {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.add-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.add-form {
	height: 1200rpx;
}

/* Adjust height as needed */
.form-row {
	display: flex;
	align-items: center;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.form-label {
	color: #333;
	width: 180rpx;
}

.form-input {
	flex: 1;
	height: 72rpx;
	padding: 0 20rpx;
	background: #fff;
	border-radius: 12rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
	color: #666;
}

.add-actions {
	display: flex;
	gap: 16rpx;
	margin-top: 20rpx;
}



.loading-wrap,
.empty-wrap,
.loading-more,
.no-more {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 40rpx 20rpx;
}

.loading-text {
	margin-top: 16rpx;
	color: #666;
	font-size: 26rpx;
}

.no-more-text {
	color: #999;
	font-size: 24rpx;
	padding: 20rpx 0;
}

/* 确保天地图插件正确显示 */
:deep(.mask) {
	position: fixed !important;
	top: 0 !important;
	left: 0 !important;
	width: 100% !important;
	height: 100% !important;
	z-index: 9999 !important;
	background-color: #FFFFFF !important;
}
</style>